package bb.lanxing.calc.fixer;

import static bb.lanxing.model.database.RouteBookPoint.BAIDU_MAX;

import com.github.mikephil.charting.utils.Utils;
import bb.lanxing.calc.data.SourcePoint;
import bb.lanxing.util.DurationUtil;

public class AltitudeFixer {
    private final float SMOOTH_FACTOR = 0.2f;
    private final float SMOOTH_FACTOR_INV = 0.8f;
    private int errorTimes;
    private SourcePoint lastSourcePoint;

    private double smooth(double last, double current) {
        return (current * SMOOTH_FACTOR) + (last * SMOOTH_FACTOR_INV);
    }

    public void fix(SourcePoint sourcePoint) {
        if (this.lastSourcePoint == null) {
            if (isAltitudeValid(sourcePoint)) {
                this.lastSourcePoint = sourcePoint;
            }
        } else if (!isAltitudeValid(sourcePoint)) {
            sourcePoint.setAltitude(this.lastSourcePoint.getAltitude());
        } else {
            fixAltitude(sourcePoint);
            smoothAltitude(sourcePoint);
            this.lastSourcePoint = sourcePoint;
        }
    }

    private void fixAltitude(SourcePoint sourcePoint) {
        double d = DurationUtil.get(sourcePoint, this.lastSourcePoint);
        double d2 = Utils.DOUBLE_EPSILON;
        if (d != Utils.DOUBLE_EPSILON) {
            d2 = (sourcePoint.getAltitude() - this.lastSourcePoint.getAltitude()) / d;
        }
        if (Math.abs(d2) > BAIDU_MAX) {
            int i = this.errorTimes + 1;
            this.errorTimes = i;
            if (i < 15) {
                sourcePoint.setAltitude(this.lastSourcePoint.getAltitude());
                return;
            }
        }
        this.errorTimes = 0;
    }

    private boolean isAltitudeValid(SourcePoint sourcePoint) {
        return sourcePoint != null && sourcePoint.getAltitude() > -300.0d && sourcePoint.getAltitude() < 6000.0d;
    }

    private void smoothAltitude(SourcePoint sourcePoint) {
        sourcePoint.setAltitude(smooth(this.lastSourcePoint.getAltitude(), sourcePoint.getAltitude()));
    }

    public void reset() {
        this.errorTimes = 0;
        this.lastSourcePoint = null;
    }
}
